/*
 * ============================================================================
 *
 *       Filename:  aclua.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年03月02日 15时39分12秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>

#include "config.h"
#include "aclua.h"
#include "log.h"

struct lua_handle_t luahandle = {0};

static void 
aclua_handle_init(lua_State **pL, int num, ...)
{
	assert(*pL == NULL);
	*pL = luaL_newstate();
	assert(*pL != NULL);
	luaL_openlibs(*pL);

	int i;
	char *script;
	va_list ap;
	va_start(ap, num);

	for(i = 0; i < num; i++) {
		script = va_arg(ap, char *);
		if(luaL_loadfile(*pL, script)) {
			sys_err("%s\n", lua_tostring(*pL, -1));
			exit(-1);
		}

		lua_call(*pL, 0, 0);
	}
	va_end(ap);
}

static void aclua_handle_free(lua_State *L)
{
	assert(L != NULL);
	lua_close(L);
}

void aclua_init()
{
	aclua_handle_init(&luahandle.L_main, 1, LUA_MAIN);
	sys_info("MODULE: ac lua init success\n");
}

void aclua_free()
{
	aclua_handle_free(luahandle.L_main);
}

void aclua_getglobal(lua_State *L, const char *name)
{
#if CMAKE_LUA_MINOR < 3
	lua_getglobal(L, name);
#else
	if(!lua_getglobal(L, name)) {
		sys_err("Can not find lua function %s\n", name);
		exit(-1);
	}
#endif
}

void aclua_pcall(lua_State *L, int nargs, int nresults)
{
	if(lua_pcall(L, nargs, nresults, 0)) {
		sys_err("%s\n", lua_tostring(L, -1));
		exit(-1);
	}
}

